package org.eliza.server.routex

import io.ktor.server.application.*
import io.ktor.server.plugins.ratelimit.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlin.time.Duration.Companion.seconds

fun Application.limiter() {
    install(RateLimit) {
        register {
            rateLimiter(limit = 1, refillPeriod = 2.seconds)
        }
        register(RateLimitName("public")) {
            rateLimiter(limit = 10, refillPeriod = 60.seconds)
        }
        register(RateLimitName("protected")) {
            rateLimiter(limit = 30, refillPeriod = 60.seconds)
            requestKey { applicationCall ->
                applicationCall.request.queryParameters["login"]!!
            }
            requestWeight { applicationCall, key ->
                when (key) {
                    "jetbrains" -> 1
                    else -> 2
                }
            }
        }
    }
    /*
    * X-RateLimit-Limit: a specified bucket capacity.
    X-RateLimit-Remaining: the number of tokens remaining in a bucket.
    X-RateLimit-Reset: a UTC timestamp (in seconds) that specifies the time of refilling a bucket.
    * */
    routing {
        route("/ratelimit") {
            rateLimit {
                get("/") {
                    val requestsLeft = call.response.headers["X-RateLimit-Remaining"]
                    call.respondText("Welcome to the home page! $requestsLeft requests left.")
                }
            }
            rateLimit(RateLimitName("public")) {
                get("/public-api") {
                    val requestsLeft = call.response.headers["X-RateLimit-Remaining"]
                    call.respondText("Welcome to public API! $requestsLeft requests left.")
                }
            }
            rateLimit(RateLimitName("protected")) {
                get("/protected-api") {
                    val requestsLeft = call.response.headers["X-RateLimit-Remaining"]
                    val login = call.request.queryParameters["login"]
                    call.respondText("Welcome to protected API, $login! $requestsLeft requests left.")
                }
            }
        }
    }
}

